package com.matuw.android.adapter.internal;

import android.os.SystemClock;
import android.view.View;

import androidx.annotation.IdRes;

import com.matuw.android.adapter.ViewAdapter;
import com.matuw.android.adapter.ViewHolder;

import java.util.ArrayList;
import java.util.List;


/**
 * @author Shihwan
 * @date 2025/4/27
 */
public class QinAdapterHelper {

    /**
     * 防重复点击的 key
     */
    protected static final int VIEW_CLICK_INTERVAL_TAG_KEY = 0x7f098100;

    /**
     * 全局设置防重点时间，默认不开启
     */
    public static long defaultDebounceClickInterval = 0;

    protected List<Integer> clickViewIds;
    protected long debounceClickInterval = defaultDebounceClickInterval;

    protected ViewAdapter.OnItemViewClickedListener listener;

    /**
     * 㧍抖点击事件
     *
     * @param interval ms
     */
    public void setDebounceClickInterval(long interval) {
        this.debounceClickInterval = interval;
    }

    public void setOnItemViewClickedListener(ViewAdapter.OnItemViewClickedListener listener) {
        this.listener = listener;
    }

    public void addClickViewIds(@IdRes int... ids) {
        if (ids != null && ids.length > 0) {
            if (clickViewIds == null) {
                clickViewIds = new ArrayList<>(ids.length);
            }

            for (int id : ids) {
                clickViewIds.add(id);
            }
        }
    }

    public void bindViewClickListener(ViewAdapter<?> adapter, ViewHolder vh, int viewType) {
        List<Integer> ids = clickViewIds;
        if (ids == null) return;

        View.OnClickListener clickListener = v -> onItemClicked(adapter, v, vh.getAdapterPosition());
        for (Integer id : ids) {
            View view = vh.getView(id);
            if (view != null) {
                view.setOnClickListener(clickListener);
            }
        }
    }

    protected void onItemClicked(ViewAdapter<?> adapter, View view, int position) {
        ViewAdapter.OnItemViewClickedListener listener = this.listener;
        if (listener == null || isClickInterval(adapter, view, position)) return;

        // 设置防点击时间
        view.setTag(VIEW_CLICK_INTERVAL_TAG_KEY, SystemClock.elapsedRealtime());
        listener.onItemViewClick(adapter, view, position);
    }

    /**
     * 是否为重复点击
     */
    protected boolean isClickInterval(ViewAdapter<?> adapter, View view, int position) {
        // 简单防重点判断，如需自定义控制，重写此方法
        Object tag;
        return debounceClickInterval > 0
                && (tag = view.getTag(VIEW_CLICK_INTERVAL_TAG_KEY)) instanceof Long
                && SystemClock.elapsedRealtime() - (long) tag < debounceClickInterval;

    }
}
